﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xeralabs.Core.Events;
using Xeralabs.Simulation.Framework;

namespace Xeralabs.Core.Entities
{
    public abstract class GDESKEntity
    {
        private ulong _guid64;

        public ulong GUID64
        {
            get { return _guid64; }
        }

        public void SetGUID64(ulong guid64)
        {
            if (_guid64 == default(ulong))
                _guid64 = guid64;
        }

        protected virtual void SendEvent(IMessage message)
        {
            SendEvent(_guid64, 0.0, Priority.Normal, message);
        }

        protected virtual void SendEvent(ulong target, IMessage message)
        {
            SendEvent(target, 0.0, Priority.Normal, message);
        }

        protected virtual void SendEvent(ulong target, double time, IMessage message)
        {
            SendEvent(target, time, Priority.Normal, message);
        }

        protected virtual void SendEvent(ulong target, double time, Priority priority, IMessage message)
        {
            SendEvent(target, time, (byte)priority, message);
        }

        private void SendEvent(ulong target, double timeStamp, byte priority, IMessage message)
        {
            GDESKEvent e = XGDESK.GetInstance().GetEvent();
            e.Input(_guid64, target, timeStamp, priority, message);
            XGDESK.GetInstance().PushEvent(e);
        }

        internal void ReciveEvent(GDESKEvent e)
        {
            if (e.Reciver != this._guid64)
            { } //do error
            else
            {
                this.ReciveEvent((IEvent)e);
                XGDESK.GetInstance().RecycleEvent(e);
            }
        }

        protected virtual void ReciveEvent(IEvent e)
        {
            if (e.Message is EndMessage)
            {
                EndMessage msg = (EndMessage)e.Message;
                if (!msg.Ended)
                {
                    if (msg.Ended = FinalizeEntity())
                    {
                        msg.EntityGUID = GUID64;
                        SendEvent(EntityManager.SingletonGUID, 0.0, (byte)Priority.Kernel, msg);
                    }
                }
            }
        }

        protected abstract bool FinalizeEntity();
    }
}